/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.miit.elearning.servlets.pages;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import ru.miit.elearning.hibernate.dao.HibernateUtil;
import ru.miit.elearning.hibernate.dao.MessageDAO;
import ru.miit.elearning.hibernate.dao.UserDAO;
import ru.miit.elearning.hibernate.dto.Message;
import ru.miit.elearning.hibernate.dto.UserIdentity;

/**
 *
 * @author pikaresk
 */
public class MessagesServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
//
//        PrintWriter out = response.getWriter();
//
//        if (true) {
//            out.println("Приносим свои извинения. Сервис временно недоступен.");
//            return;
//        }

        Session session = null;

        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            MessageDAO messageDAO = new MessageDAO(session);
            int userId = messageDAO.findUserIdByLogin(request.getRemoteUser());

            List<Message> messagesList = messageDAO.findMessagesByUser(userId);

            List<UserIdentity> usersList = null;
            String idRecipientString = request.getParameter("idRecipient");
            UserDAO userDAO = new UserDAO(session);
            if (idRecipientString != null && idRecipientString.length() > 0) {
                int idRecipient = Integer.parseInt(idRecipientString);
                usersList = new ArrayList<UserIdentity>(1);
                usersList.add(userDAO.findUserById(idRecipient));

                String answerToString = request.getParameter("answerTo");
                if (answerToString != null && answerToString.length() > 0) {
                    try {
                        int answerTo = Integer.parseInt(answerToString);
                        request.setAttribute("subject", "Re: " + messageDAO.findMessage(answerTo).getSubject());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                answerToString = null;


                request.setAttribute("showForm", true);
            } else {
                if (request.getParameter("showFormAsked") != null && request.getParameter("showFormAsked").equals("y")) {
                    usersList = userDAO.findAllUsers();
                    request.setAttribute("showForm", true);
                }
            }
            userDAO = null;

            request.setAttribute("messageList", messagesList);
            request.setAttribute("userList", usersList);

            getServletContext().getRequestDispatcher("/messages.jsp").forward(request, response);
            if (session != null && session.isOpen()) {
                session.getTransaction().commit();
            }


        } catch (Exception e) {
            getServletContext().setAttribute("message", "Произошла ошибка запроса личных сообщений");
            getServletContext().getRequestDispatcher("/messages.jsp").forward(request, response);
            if (session != null && session.isOpen()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();

        } finally {
//            out.close();
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
